<?php

namespace app\admin\service;

use app\admin\dao\UserDao;
use app\common\model\User;
use ShidianUtil\Utils\RandUtil;
use ShidianUtil\Utils\StringUtil;
use think\exception\ValidateException;

/**
 * Class SessionService
 * @package app\session\service
 */
class SessionService
{

    private UserDao $userDao;
    private AccessService $accessService;

    public function __construct(UserDao $userDao, AccessService $accessService)
    {

        $this->userDao = $userDao;
        $this->accessService = $accessService;
    }

    /**
     * 登录
     * @param array $params
     * @return  \app\common\model\User
     */
    public function add(array $params): User
    {
        $username = $params['username'] ?? null;
        $password = $params['password'] ?? null;

        if (is_blank($username)) {
            throw new ValidateException('请输入用户名');
        }

        if (is_blank($password)) {
            throw new ValidateException('请输入密码');
        }

        // 查询
        $record = User::field(true)
            ->where('username', $username)
            ->find();

        if (is_null($record)) {
            throw new ValidateException('用户不存在');
        }

        if ($record->status == 0) {
            throw new ValidateException('用户已被冻结');
        }

        if ($record->isAdmin == 0 && !is_id($record->roleId)) {
            throw new ValidateException('角色被删除，请联系管理员');
        }

        // 验证
        $this->checkSignVerifier($record->password, $record->salt, $password);

        $record->token = RandUtil::token(true);
        $record->save();

        // TODO 记录登录成功的日志

        $record = $this->userDao->findByLogin($record->id);

        // 权限
        $record->setRelation('pages', $this->accessService->index($record));

        return $record;
    }

    /**
     * 验证密码
     * @param string $user_password 用户密码
     * @param string $user_slat
     * @param string $password 输入的密码
     * @return void
     */
    private function checkSignVerifier(string $user_password, string $user_slat, string $password)
    {
        $hash = md5(md5($password) . $user_slat);

        if (!StringUtil::equals($hash, $user_password)) {
            throw new ValidateException('登录密码错误');
        }
    }
}
